import { useState } from 'react';
import { unwrapResult } from '@reduxjs/toolkit';
import { Form, Input, Button, Checkbox, App } from 'antd';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { AiFillLock, AiOutlineUser } from 'react-icons/ai';
import { ILoginReqParams, IUserInfo } from 'src/interface';
import { AppDispatch } from 'src/store';
import { login, getUserInfo } from 'src/store/action';

interface IProps {
  redirect?: string | null;
}

export default function LoginForm(props: IProps) {
  const { redirect } = props;

  const [loading, setLoading] = useState(false);
  const { notification } = App.useApp();
  const dispatch = useDispatch<AppDispatch>();
  const navigate = useNavigate();
  const { t } = useTranslation();

  const onSubmit = async (values: ILoginReqParams) => {
    setLoading(true);
    const { username, password } = values;
    try {
      const action = await dispatch(login({ username, password }));
      if (action.payload) {
        const userInfos = await (dispatch(getUserInfo()).then(unwrapResult) as Promise<IUserInfo>);
        navigate(redirect ? redirect : '/');
        notification.success({
          message: t('login.success_title'),
          description: `${t('login.success_descript')}: ${userInfos.nickname}`,
          duration: 3,
        });
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };
  return (
    <>
      <Form
        size={'large'}
        initialValues={{ remember: true, username: 'test', password: 'sloth123456' }}
        onFinish={onSubmit}
        className="mt-4">
        <Form.Item
          name="username"
          rules={[{ required: true, message: t('login.user_placeholder') }]}>
          <Input prefix={<AiOutlineUser />} placeholder={t('login.user_placeholder')} />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: t('login.pass_placeholder') }]}>
          <Input
            prefix={<AiFillLock />}
            type="password"
            placeholder={t('login.pass_placeholder')}
          />
        </Form.Item>
        <Form.Item>
          <div className="flex justify-between">
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>{t('login.remember')}</Checkbox>
            </Form.Item>
            <a className="login-form-forgot" href="">
              {t('login.forget')}
            </a>
          </div>
        </Form.Item>
        <Form.Item>
          <Button
            loading={loading}
            type="primary"
            block
            size="large"
            htmlType="submit"
            className="login-form-button">
            {t('login.signin')}
          </Button>
        </Form.Item>
      </Form>
    </>
  );
}
